﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using UIT.Events.Keyboard;
using JQueryControlToolkit;
using UIT.Controls;
using UIT.Controls.Template;
using UIT.Controls.Containers;

namespace UIT.Web.Renderers
{
    public static class KeyCommandBindings
    {
        public static void RenderKeyBindings(this UIT.Controls.IControl control)
        {
            DomResult operations = new DomResult();
            operations.AddParameter("index");
            operations.AddParameter("self");
            foreach (KeyCommandBinding item in control.KeyCommandBindings)
            {
                operations.AddOperation("keyDown", new object[] { item.CommandName, new DomOperation() { Code = "self" }, new DomOperation() { Code = typeof(Keys).FullName + "." + item.Key }, new DomOperation() { Code = "arguments" } }, "keyDown");
                //operations.AddOperation("Command.register", new object[]{ item.CommandName, });
            }
            if (operations.Operations.Count > 0)
            {
                if (string.IsNullOrEmpty(control.Id))
                    control.Id = "ctrl" + control.GetHashCode();

                ScriptManager.RegisterCall("keyevents"+control.GetHashCode(), new JQueryControlToolkit.JQuery("#" + control.Id).Each(operations));
                if (!control.TabIndex.HasValue)
                    control.TabIndex = control.GetAutoTabIndex();
            }
        }

        private static int GetAutoTabIndex(this IControl control)
        {
            IContainer parent;
            do
            {
                parent = control.Parent;
                if (parent is DataTemplateInstance)
                {
                    control = parent;
                    continue;
                }
                return ((IControlContainer)parent).Children.IndexOf(control);
            }
            while (parent != null);
            return 0;
        }
    }
}
